package kr.hyunist.musicplayexer;

import java.util.ArrayList;

import kr.hyunist.musicplayexer.Adapter.ListAdapter;
import kr.hyunist.musicplayexer.Application.MediaApplication;
import kr.hyunist.musicplayexer.DTO.MyMusic;
import kr.hyunist.musicplayexer.Util.Util;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class ListMainActivity extends Activity {

	private boolean isShowLyricsWindow = false; // 가사창 보임/숨김상태
	public static final String TAG = "MediaProject";
	final String SERVICE_ACTIVITY = "kr.hyunist.musicplayexer.MusicService";

	ArrayList<MyMusic> arList; // 음악들이 담겨있는 배열리스트
	ListView list; // 리스트뷰
	MyMusic music; // 음악의 정보
	ListAdapter adapter; // 커스텀 어댑터
	Intent intent = null; // playDetail을 띄우기 위한 인텐트 객체
	MediaApplication app; // application객체
	SeekBar mSeekProgress; // 진행시크바
	Handler mHandler; // 시크바 상태 변경 핸들러
	Runnable runnable; // 시크바 변경 스레드
	TextView nowTime; // 현재 재생 시간
	Intent sIntent;
	ImageView playIcon;
	TextView mTxtLyrics;
	
	// 현재 재생되는 음악란의 뷰
	ImageView nowAlbumImg;
	TextView nowTitle;
	TextView nowSinger;
	TextView nowPlayTime;
	ImageView playingIcon;
	Button nowPlayingbtn;
	Button nowPrevbtn;
	Button nowNextbtn;

	int currentIndex;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 어플리케이션 객체
		app = (MediaApplication) getApplication();
		Log.d(ListMainActivity.TAG, "앱실행 되자마자 메인 리스트에 app.mService 상태 : "
				+ app.mService);
		Log.d(ListMainActivity.TAG, "앱실행 되자마자 메인 리스트에 app.mPlayer 주소 : "
				+ app.mPlayer);
		
		mTxtLyrics = (TextView) findViewById(R.id.txtLyrics);
		playingIcon = (ImageView) findViewById(R.id.playingicon);
		nowPlayingbtn = (Button) findViewById(R.id.nowplaypauseicon);
		nowTime = (TextView) findViewById(R.id.nowTime);
		nowPlayTime = (TextView) findViewById(R.id.nowplayTime);

		startActivity(new Intent(ListMainActivity.this, IntroActivity.class));

		if (app.getCurrentPosition() >= 0) {
			if (app.mPlayer != null && app.mPlayer.isPlaying()) {
				// CurrentPositionPlayBack();
				seekProgress();
				nowPlayingbtn
						.setBackgroundResource(R.drawable.nowpause_selector);
			} else if (app.mPlayer != null && !app.mPlayer.isPlaying()) {

			}
		}

		// 어플리케이션 객체에 arList 등록
		arList = new ArrayList<MyMusic>();
		app.setArList(arList);

		adapter = new ListAdapter(this, app.getArList());
		list = (ListView) findViewById(R.id.list);
		list.setAdapter(adapter);

		// 서비스로 연결
		if (app.mService == null) {
			sIntent = new Intent(SERVICE_ACTIVITY);
			startService(sIntent);
			bindService(sIntent, serviceCon, BIND_AUTO_CREATE);
		}

		// 진행 시크바
		mSeekProgress = (SeekBar) findViewById(R.id.songprogress);
		mSeekProgress.setOnSeekBarChangeListener(mOnProgressSeek);

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// 어플리케이션 객체에서 리스트 포지션을 전역으로 설정
				app.setCurrentPosition(position);

				Log.d(ListMainActivity.TAG, "메인액티비티에 app : " + app);
				Log.d(ListMainActivity.TAG, "메인액티비티에 app.mService : "
						+ app.mService);
				Log.d(ListMainActivity.TAG, "메인액티비티 음악 데이터 : "
						+ app.getArList().get(app.getCurrentPosition())
								.getData());
				Log.d(ListMainActivity.TAG,
						"전역 position : " + app.getCurrentPosition());

				try {

					// 음악 실행
					app.mService.onListItemSelectplayBackMusic(app
							.getCurrentPosition());
					nowPlayingbtn
							.setBackgroundResource(R.drawable.nowpause_selector);

					String path = Util.getRealPathFromURI(
							app.getArList().get(app.getCurrentPosition())
									.getUri(), getBaseContext());
					String lyrics = Util.getLyricsTagRead(path);
					/*if (lyrics == null) {
						mTxtLyrics.setText("지원되는 가사가 없습니다.");
					} else {
						mTxtLyrics.setText(lyrics);
					}*/
					
					Log.d(ListMainActivity.TAG, "가사 호출 : " + lyrics);
					
					if (!lyrics.equals("")) {
						mTxtLyrics.setText(lyrics);
						isShowLyricsWindow = true;
					} else {
						mTxtLyrics.setText("지원되는 가사 정보가 없음!");
						isShowLyricsWindow = false;
					}

					// playingIcon.setVisibility(View.VISIBLE);

					Log.d(ListMainActivity.TAG, "mService객체 : " + app.mService);
					Log.d(ListMainActivity.TAG, "isPlaying의 상태는? : "
							+ app.mPlayer.isPlaying());

				} catch (Exception e) {

				}

				CurrentPositionPlayBack();
				seekProgress();

				// 앱을 종료했다가 실행했을때 음악이 재생중이면 상태가 하단에 출력
				/*
				 * if(app.mPlayer != null){ CurrentPositionPlayBack();
				 * mSeekProgress(); } else { CurrentPositionPlayBack(); }
				 */

			}

		});

	}

	private void seekProgress() {
		// 진행 시크바
		mHandler = new Handler();
		runnable = new Runnable() {

			@Override
			public void run() {
				mHandler.postDelayed(runnable, 200);
				try {
					if (app.mPlayer.isPlaying()) {
						mSeekProgress.setMax(app.mPlayer.getDuration());
						mSeekProgress.setProgress(app.mPlayer
								.getCurrentPosition());
					}

					nowTime.setText(Util.milliSecToTime(String
							.valueOf(app.mPlayer.getCurrentPosition())));
				} catch (Exception e) {

				}

			}
		};

		mHandler.postDelayed(runnable, 200);
	}

	// 진행 시크바 이벤트 처리
	SeekBar.OnSeekBarChangeListener mOnProgressSeek = new OnSeekBarChangeListener() {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				app.mPlayer.seekTo(progress);
			}
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

	};

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(ListMainActivity.TAG, "ListMainActivity onResume상태");
		CurrentPositionPlayBack();
	}

	// 하단 현재 재생 되는 음원 설정
	public void CurrentPositionPlayBack() {
		// 음원에 대한 비트맵 이미지 변환
		Bitmap nowAlbumArt = Util.getArtworkQuick(ListMainActivity.this,
				Integer.parseInt((app.getArList().get(app.getCurrentPosition())
						.getAlbumID())), 200, 200);

		// 재생되는 음악 이미지
		nowAlbumImg = (ImageView) findViewById(R.id.nowalbumart);
		if (nowAlbumArt == null) {
			nowAlbumImg.setImageResource(R.drawable.noimage);
		} else {
			nowAlbumImg.setImageBitmap(nowAlbumArt);
		}

		// 현재 재생되고 있는 음악이미지비트맵을 클릭했을때 PlayDetail 액티비티를 띄움. 정보를 putExtra로 전송
		nowAlbumImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				intent = new Intent(getApplication(), PlayDetail.class);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_down,
						R.anim.slide_out_top);
			}

		});

		// 현재 재생 되는 음악의 정보를 하단에 출력
		nowTitle = (TextView) findViewById(R.id.nowtitle);
		nowTitle.setText(app.getArList().get(app.getCurrentPosition())
				.getMusicTitle());
		nowTitle.setSelected(true);

		nowSinger = (TextView) findViewById(R.id.nowsinger);
		nowSinger.setText(app.getArList().get(app.getCurrentPosition())
				.getArtist());

		nowPlayTime.setText(app.getArList().get(app.getCurrentPosition())
				.getPlayTime());
	}

	// 하단 현재 재생 되는 음악란 버튼 이벤트
	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.nowplaypauseicon:
			try {
				app.mService.playAndPause();

				if (app.mPlayer.isPlaying()) {
					nowPlayingbtn
							.setBackgroundResource(R.drawable.nowpause_selector);
				} else {
					nowPlayingbtn
							.setBackgroundResource(R.drawable.nowplayingicon_selector);
				}

				/*
				 * if (app.mPlayer != null) { if (app.mService.isPlaying() ==
				 * false) { app.mService.start();
				 * nowPlayingbtn.setBackgroundResource
				 * (R.drawable.nowpause_selector); } else {
				 * app.mService.pause();
				 * nowPlayingbtn.setBackgroundResource(R.drawable
				 * .nowplayingicon_selector); } } else {
				 * app.mService.onListItemSelectplayBackMusic
				 * (app.getCurrentPosition());
				 * nowPlayingbtn.setBackgroundResource
				 * (R.drawable.nowpause_selector); }
				 * 
				 * if (app.getCurrentPosition() >= 0) { if (app.mPlayer != null
				 * && app.mPlayer.isPlaying()) { app.mPlayer.stop();
				 * nowPlayingbtn
				 * .setBackgroundResource(R.drawable.nowplayingicon_selector); }
				 * else if (app.mPlayer != null && !app.mPlayer.isPlaying()) {
				 * app
				 * .mService.onListItemSelectplayBackMusic(app.getCurrentPosition
				 * ()); nowPlayingbtn.setBackgroundResource(R.drawable.
				 * nowstopicon_selector); }
				 * 
				 * }
				 */

			} catch (Exception e) {
				ErrorToast("재생에 실패 했군여! 죄송합니다!");
			}
			break;

		case R.id.nowprevicon:
			try {
				app.mService.prev();
				app.mPlayer.reset();
				app.mService.onListItemSelectplayBackMusic(app
						.getCurrentPosition());
				CurrentPositionPlayBack();
			} catch (RemoteException e) {
				ErrorToast("이전곡 재생에 실패했습니다. 죄송합니다!");
			}
			break;

		case R.id.nownexticon:
			try {
				app.mService.next();
				app.mPlayer.reset();
				app.mService.onListItemSelectplayBackMusic(app
						.getCurrentPosition());
				CurrentPositionPlayBack();
			} catch (RemoteException e) {
				ErrorToast("다음곡 재생에 실패했습니다. 죄송합니다!");
			}
			break;

		case R.id.showLyrics:
			if (app.getCurrentPosition() >= 0) {
				if (app.mPlayer != null && app.mPlayer.isPlaying()) {
					if (!isShowLyricsWindow) {
						mTxtLyrics.setVisibility(View.VISIBLE);
						isShowLyricsWindow = true;
					} else {
						mTxtLyrics.setVisibility(View.GONE);
						isShowLyricsWindow = false;
					}
				} else if (app.mPlayer != null && !app.mPlayer.isPlaying()) {

				}
			}
			break;
		}
	}

	// 서비스 커넥션
	ServiceConnection serviceCon = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			app.mService = IMediaService.Stub.asInterface(service);
			Log.d(ListMainActivity.TAG, "서비스 연결 성공했으면 이거 뜰꺼임!");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			app.mService = null;
			Log.d(ListMainActivity.TAG, "서비스 Disconnected 이거 뜰꺼임!");
		}

	};

	// 에러처리 토스트
	protected void ErrorToast(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (app.mService != null) {
			unbindService(serviceCon);
			serviceCon = null;
			app.mService = null;
			Log.d(ListMainActivity.TAG,
					"메인 리스트가 종료 된 후 app.getCurrentPosition : "
							+ app.getCurrentPosition());
			Log.d(ListMainActivity.TAG, "메인 리스트가 종료 된 후 app상태 : " + app);
		}
	}

}
